package client;

import common.Message;
import common.MessageType;
import util.Utility;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientConnectServiceThread extends Thread{
    Socket socket;


    public ClientConnectServiceThread(Socket socket)
    {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while (true)
            {
                //得不到数据就会阻塞
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message  message = (Message)objectInputStream.readObject();
                //得到在线用户后操作
                if (message.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND))
                {
                    String content = message.getContent();
                    String[] split = content.split(" ");
                    System.out.println("==================在线人员有=================");
                    for (String s : split) {
                        if(s.equals(message.getGetter()))
                        {
                            System.out.println(s+"(本人)");
                        }else {
                            System.out.println(s);
                        }
                    }

                }
                //接受他人发送的消息
                else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES))
                {
                    String sender = message.getSender();
                    System.out.println("用户:"+sender+"对俺说"+message.getContent());
                }
                //接受他人发送的文件
                else if (message.getMesType().equals(MessageType.MESSAGE_FILE))
                {
                    String sender = message.getSender();
                    byte[] fileByte = message.getFileByte();
                    FileOutputStream fileOutputStream = new FileOutputStream("d:\\dundun1.jpg");
                    fileOutputStream.write(fileByte);
                    System.out.println("用户"+sender+"发来一个文件成功保存在d:\\dundun1.jpg");
                    fileOutputStream.close();
                }
                else {
                    System.out.println("暂时没处理");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}
